package org.sky.wall.visual.util


import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.os.Bundle
import android.service.wallpaper.WallpaperService
import android.util.Log
import android.view.MotionEvent
import android.view.Surface
import android.view.SurfaceHolder
import android.view.WindowManager
import androidx.core.content.ContextCompat
import java.util.Arrays

class CameraLiveWallpaper : WallpaperService() {
	
	override fun onCreateEngine(): Engine {
		return CameraEngine()
	}
	
	inner class CameraEngine : Engine() {
		private var cameraDevice: CameraDevice? = null
		private var cameraCaptureSession: CameraCaptureSession? = null
		
		private val surfaceCallback = object : SurfaceHolder.Callback {
			override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
				// Configure camera preview here
				startPreview(holder.surface)
			}
			
			override fun surfaceCreated(holder: SurfaceHolder) {
				// Surface is created
			}
			
			override fun surfaceDestroyed(holder: SurfaceHolder) {
				// Surface is destroyed
				stopPreview()
			}
		}
		
		private val stateCallback = object : CameraDevice.StateCallback() {
			override fun onOpened(camera: CameraDevice) {
				cameraDevice = camera
				createCameraPreviewSession()
			}
			
			override fun onDisconnected(camera: CameraDevice) {
				cameraDevice?.close()
				cameraDevice = null
			}
			
			override fun onError(camera: CameraDevice, error: Int) {
				cameraDevice?.close()
				cameraDevice = null
			}
		}
		
		override fun onCreate(surfaceHolder: SurfaceHolder) {
			super.onCreate(surfaceHolder)
			surfaceHolder.addCallback(surfaceCallback)
			setTouchEventsEnabled(true)
		}
		
		override fun onTouchEvent(event: MotionEvent) {
			super.onTouchEvent(event)
			// Handle touch events: click to take a photo, long press to take a photo
		}
		
		override fun onDestroy() {
			super.onDestroy()
			stopPreview()
		}
		
		@SuppressLint("MissingPermission")
		private fun startPreview(surface: Surface) {
			val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
			val cameraId = getCameraId(manager)
			try {
				manager.openCamera(cameraId, stateCallback, null)
			} catch (e: CameraAccessException) {
				Log.d("xianban", "连接相机失败")
				e.printStackTrace()
			}
		}
		
		private fun stopPreview() {
			cameraDevice?.close()
			cameraCaptureSession?.close()
		}
		
		private fun createCameraPreviewSession() {
			try {
				val surface = surfaceHolder.surface
				val captureRequestBuilder = cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
				captureRequestBuilder?.addTarget(surface)
				
				cameraDevice?.createCaptureSession(Arrays.asList(surface), object : CameraCaptureSession.StateCallback() {
					override fun onConfigured(session: CameraCaptureSession) {
						if (cameraDevice == null) return
						
						cameraCaptureSession = session
						captureRequestBuilder?.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)
						
						try {
							captureRequestBuilder?.build()
								?.let { session.setRepeatingRequest(it, null, null) }
						} catch (e: CameraAccessException) {
							e.printStackTrace()
						}
					}
					
					override fun onConfigureFailed(session: CameraCaptureSession) {
						// Handle configuration failure
					}
				}, null)
			} catch (e: CameraAccessException) {
				e.printStackTrace()
			}
		}
		
		private fun getCameraId(manager: CameraManager): String {
			val cameraIds = manager.cameraIdList
			for (id in cameraIds) {
				val characteristics = manager.getCameraCharacteristics(id)
				val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
				if (facing == CameraCharacteristics.LENS_FACING_BACK) {
					return id
				}
			}
			return cameraIds[0] // Default to the first camera if no back-facing camera is found
		}
	}
}
